import React from 'react';
import 'ol/ol.css';
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import {defaults as defaultControls, Attribution, Zoom} from 'ol/control.js';

import GbaseLayers from './GbaseLayers';
import Projection from "ol/proj/Projection";
import DragPan from "ol/interaction";

class Gmap {
  constructor(target) {
    this.view = null;
    this.map = null;
    this.baseLayer = null;
    this.initMap(target);
  }

  //初始化地图
  initMap = (target = 'map') => {
    var projection = new Projection({
      code: 'EPSG:4326',
      units: 'degrees'
    });
    this.view = new View({
      projection: projection,
      center: [115.591172, 37.594792],
      zoom: 14,
      minZoom: 12,
      maxZoom: 18,
    });
    this.map = new Map({
      layers: new GbaseLayers().HistoryImage,
      target: target,
      view: this.view,
      controls: defaultControls({
        attribution: false,
        zoom: false
      }).extend([
        new Attribution({collapsible: false})
      ]),
    });
    this.map.addControl(new Zoom({zoomInTipLabel: '放大', zoomOutTipLabel: '缩小'}));
  }
  //禁止鼠标拖动
  getPan = () => {
    let pan;
    this.map.getInteractions().forEach(function (element, index, array) {
      if (element instanceof DragPan) {
        pan = element;
      }
    })
    return pan;
  }
  //设置底图
  setBaseLayer = (layer = new GbaseLayers().TDT_IMAGE) => {
    if (this.baseLayer) this.map.removeLayer(this.baseLayer);
    this.baseLayer = layer;
    this.map.addLayer(layer);
  }
  //设置底图
  setAllLayersInvisible = () => {
    this.map.getLayers().forEach((layer) => {
      layer.setVisible(false);
    })
    this.baseLayer.setVisible(true);
  }
  //设置中心点
  setCenter = (position) => {
    this.map.getView().setCenter(position);
  }
  //
  removeAllOverlays = () => {
    var isCear = false;
    while (!isCear) {
      var overlays = this.map.getOverlays().getArray();
      if (overlays.length > 0) {
        overlays.forEach((overlay) => {
          this.map.removeOverlay(overlay);
        })
      } else {
        isCear = true;
      }
    }
  }
  removeOverlaysById = (id) => {
    var isCear = false;
    while (!isCear) {
      var overlays = this.map.getOverlays().getArray();
      if (overlays.length > 0 && this.hasOverlay(id)) {
        overlays.forEach((overlay) => {
          if (overlay.id == id) this.map.removeOverlay(overlay);
        })
      } else {
        isCear = true;
      }
    }
  }
  hasOverlay = (id) => {
    var has = false;
    var overlays = this.map.getOverlays().getArray();
    overlays.forEach((overlay) => {
      if (overlay.id == id) {
        has = true;
      }
    })
    return has;
  }
}

export default Gmap;
